package cn.jobstart.es.listener;

import cn.jobstart.common.*;
import cn.jobstart.enums.*;
import cn.jobstart.es.listener.event.*;
import cn.jobstart.es.model.ResumeEs;
import cn.jobstart.es.service.IResumeEsService;
import cn.jobstart.model.ResumeBasic;
import cn.jobstart.model.TalentSubscriptionTask;
import cn.jobstart.modelExt.PersonExt;
import cn.jobstart.modelExt.ResumeBasicExt;
import cn.jobstart.pubInter.exception.SkException;
import cn.jobstart.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author sunke
 * @version 1.0
 * @Description
 * @date 2023-09-06 16:24
 */
@Slf4j
@Component
public class ResumeEsListener implements IEsListener<ResumeEsEvent> {


    private static final ExecutorService executor
            = Executors.newScheduledThreadPool(1000);


    private static final byte[] LOCK = new byte[0];
    @Resource
    private IResumeBasicService resumeBasicService;
    @Resource
    private IResumeEsService resumeEsService;
    /**
     * 能力标签
     */
    @Resource
    private IResumeCapabilityLabelService resumeCapabilityLabelService;
    @Resource
    private IResumeCertificateService resumeCertificateService;
    /**
     * 教育经历
     */
    @Resource
    private IResumeEducationalExperienceService resumeEducationalExperienceService;
    @Resource
    private IResumeEmploymentIntentionService resumeEmploymentIntentionService;
    /**
     * 实习经历
     */
    @Resource
    private IResumeIntershipService resumeIntershipService;
    @Resource
    private IResumeProfessionalSkillsService resumeProfessionalSkillsService;
    /**
     * 项目经历
     */
    @Resource
    private IResumeProjectExperienceService resumeProjectExperienceService;
    /**
     * 培训经历
     */
    @Resource
    private IResumeTrainingExperienceService resumeTrainingExperienceService;
    /**
     * 工作经历
     */
    @Resource
    private IResumeWorkExperienceService resumeWorkExperienceService;
    @Resource
    private IResumeAssociationActivityService resumeAssociationActivityService;
    @Resource
    private IPersonService personService;


    public ResumeBasicExt initResumeBasic(String resumeId) throws SkException {

        ResumeBasicExt resumeBasic = resumeBasicService.getDetail(resumeId);
        String personId = resumeBasic.getPersonId();
        if (StringUtil.isNullOrEmpty(personId)) {
            PersonExt person = new PersonExt();
            person.setId(IdGen.uuid());
            person.setTruename(resumeBasic.getTruename());
            person.setPhone(resumeBasic.getMobile());
            personId = person.getId();
            personService.insert(person);
        }
        resumeBasic.setPersonId(personId);

        if (StringUtil.isNotObjEmpty(resumeBasic.getEducation())) {
            resumeBasic.setEducationFlag(ResumeBasicEducationFlagEnum.getDescByType(resumeBasic.getEducation()));
        }
        if (StringUtil.isNotObjEmpty(resumeBasic.getSex())) {
            resumeBasic.setSexFlag(ResumeBasicSexFlagEnum.getDescByType(resumeBasic.getSex()));
        }


        String jobYear = resumeBasic.getJobYear();
        if (StringUtil.isNotObjEmpty(jobYear) && StringUtil.isNullOrEmpty(resumeBasic.getWorkExperienceFlag())) {
            jobYear = StringUtil.replaceAll(jobYear, "年", "");
            resumeBasic.setWorkExperienceFlag(AdminJobWorkExperienceFlagEnum.getTypeByYear(NumberUtil.parseInt(jobYear)));
        }

        if (StringUtil.isNotObjEmpty(resumeBasic.getPolitics())) {
            resumeBasic.setPoliticsFlag(ResumeBasicPoliticsFlagEnum.getDescByType(resumeBasic.getPolitics()));
        }

        if (StringUtil.isNotObjEmpty(resumeBasic.getMarriage())) {
            resumeBasic.setMarriageFlag(ResumeBasicMarriageFlagEnum.getDescByType(resumeBasic.getMarriage()));
        }
        if(StringUtil.isNotObjEmpty(resumeBasic.getBirthday())){
            resumeBasic.setAge(YXDate.getYearSub(resumeBasic.getBirthday(),new Date()));
        }


        return resumeBasic;
    }

    /**
     * 添加
     *
     * @param resumeId
     * @throws SkException
     */
    private void baseAdd(String resumeId) throws SkException {


        ResumeBasicExt resumeBasic = initResumeBasic(resumeId);

        String personId = resumeBasic.getPersonId();


        ResumeEs resumeEs = new ResumeEs();
        BeanUtils.copyPropertiesIgnoreNull(resumeBasic, resumeEs);
        resumeEs.setId(resumeId);
        resumeEs.setThirdAccountId(resumeBasic.getKzpStudentId());


        resumeEsService.insert(resumeEs);

        resumeBasicService.updateDataById(SkMap.getInstance().addObjToMap(ResumeBasic.ES_FLAG, ResumeBasicEsFlagEnum.Y.getType()).addObjToMap(ResumeBasic.PERSON_ID, personId)

                , resumeId);

    }


    public void baseAddAll(String resumeId) throws SkException {


        doExecute(resumeId);


       /* executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    doExecute(resumeId);
                } catch (SkException e) {

                }
            }
        });*/


    }

    /**
     * 添加 所有相关
     *
     * @param resumeId
     * @throws SkException
     */
    private void doExecute(String resumeId) throws SkException {


        ResumeBasicExt resumeBasic = initResumeBasic(resumeId);

        String personId = resumeBasic.getPersonId();

        ResumeEs resumeEs = new ResumeEs();
        BeanUtils.copyPropertiesIgnoreNull(resumeBasic, resumeEs);
        resumeEs.setThirdAccountId(resumeBasic.getKzpStudentId());



      /*  String jobYear = resumeBasic.getJobYear();
        if (StringUtil.isNotObjEmpty(jobYear)) {
            jobYear = StringUtil.replaceAll(jobYear, "年", "");
            resumeEs.setWorkExperienceFlag(AdminJobWorkExperienceFlagEnum.getTypeByYear(NumberUtil.parseInt(jobYear)));
        }*/


        /**
         * 在校经历
         */
        String associationActivityStr = resumeAssociationActivityService.getAssociationActivityStrByResumeId(resumeId);
        if (StringUtil.isNotObjEmpty(associationActivityStr)) {
            resumeEs.setAssociationActivity(associationActivityStr);
        }

        /**
         * 能力标签
         */
        String labelStr = resumeCapabilityLabelService.getResumeCapabilityLabelStrByResumeId(resumeId);
        if (StringUtil.isNotObjEmpty(labelStr)) {
            resumeEs.setCapabilityLabel(labelStr);
        }


        //添加证书
        String certificateStr = resumeCertificateService.getCertificateStrByResumeId(resumeId);
        if (StringUtil.isNotObjEmpty(certificateStr)) {
            resumeEs.setCertificate(certificateStr);
        }

        //添加教育经历
        Map<String, Object> educationalMap = resumeEducationalExperienceService.getEducationalExperienceStrByResumeId(resumeId);
        if (StringUtil.isNotObjEmpty(educationalMap)) {
            resumeEs.setSchool(StringUtil.toString(educationalMap.get("school")));
            resumeEs.setSpeciality(StringUtil.toString(educationalMap.get("speciality")));

            resumeEs.setEducation(StringUtil.toString(educationalMap.get("education")));
            resumeEs.setEducationFlag(ResumeBasicEducationFlagEnum.getDescByType(resumeEs.getEducation()));
            resumeEs.setEducationalExperience(StringUtil.toString(educationalMap.get("info")));
            resumeEs.setSchoolLabel(StringUtil.toString(educationalMap.get("label")));
        }

        //求职意向
        String employmentIntentionStr = resumeEmploymentIntentionService.getEmploymentIntentionStrByResumeId(resumeId);
        if (StringUtil.isNotObjEmpty(employmentIntentionStr)) {
            resumeEs.setEmploymentIntention(employmentIntentionStr);
        }

        //实习经历
        String intershipStr = resumeIntershipService.getIntershipStrByResumeId(resumeId);
        if (StringUtil.isNotObjEmpty(intershipStr)) {
            resumeEs.setInternship(intershipStr);
        }

        //专业技能
        String professionalSkillsStr = resumeProfessionalSkillsService.getProfessionalSkillsStrByResumeId(resumeId);
        if (StringUtil.isNotObjEmpty(professionalSkillsStr)) {
            resumeEs.setProfessionalSkills(professionalSkillsStr);
        }

        //项目经历
        String projectExperienceStr = resumeProjectExperienceService.getProjectExperienceStrByResumeId(resumeId);
        if (StringUtil.isNotObjEmpty(projectExperienceStr)) {
            resumeEs.setProjectExperience(projectExperienceStr);
        }
        //培训经历
        String trainingExperienceStr = resumeTrainingExperienceService.getTrainingExperienceStrByResumeId(resumeId);
        if (StringUtil.isNotObjEmpty(trainingExperienceStr)) {
            resumeEs.setTrainingExperience(trainingExperienceStr);
        }
        //工作经历
        String workExperienceStr = resumeWorkExperienceService.getWorkExperienceStrByResumeId(resumeId);
        if (StringUtil.isNotObjEmpty(workExperienceStr)) {
            resumeEs.setWorkExperience(workExperienceStr);
        }

        resumeEs.setId(resumeId);
        resumeEs.setPersonId(personId);
        // synchronized (LOCK) {
        resumeEsService.insert(resumeEs);
        // }

        resumeBasicService.updateDataById(SkMap.getInstance().addObjToMap(ResumeBasic.ES_FLAG, ResumeBasicEsFlagEnum.Y.getType()).addObjToMap(ResumeBasic.PERSON_ID, personId)

                , resumeId);


        //去更新订阅得到的简历数
       String talentSubscriptionTaskId= resumeEs.getTalentSubscriptionTaskId();
        if(StringUtil.isNotObjEmpty(resumeEs.getTalentSubscriptionTaskId())){

            talentSubscriptionTaskService.updateDataById(
                    SkMap.getInstance().addObjToMap(TalentSubscriptionTask.RESUME_COUNT, resumeBasicService.getCountByTalentSubscriptionTaskId(talentSubscriptionTaskId))
                    , talentSubscriptionTaskId);



        }


    }


    @Resource
    private ITalentSubscriptionTaskService talentSubscriptionTaskService;

    /**
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @EventListener(ResumeEsEvent.class)
    public void action(ResumeEsEvent event) {
        try {
            String resumeId = event.getResumeId();

            if (event instanceof ResumeBaseEsAddAllEvent) {
                baseAddAll(resumeId);
                return;
            }

            if (event instanceof ResumeBaseAddEvent) {
                baseAdd(resumeId);
                return;
            }
            if (event instanceof ResumeEsDeleteEvent) {
                resumeEsService.delete(resumeId);
                return;
            }


            if (event instanceof ResumeBaseEsUpdateEvent) {
                resumeBaseUpdate(resumeId);
                return;
            }


            if (event instanceof ResumeAssociationActivityEsUpdateEvent) {

                ResumeEs resumeEs = resumeEsService.detailById(resumeId);
                /**
                 * 在校经历
                 */
                String associationActivityStr = resumeAssociationActivityService.getAssociationActivityStrByResumeId(resumeId);
                if (StringUtil.isNotObjEmpty(associationActivityStr)) {
                    resumeEs.setAssociationActivity(associationActivityStr);
                    resumeEsService.update(resumeEs, resumeEs.getId());
                }

                return;
            }


            if (event instanceof ResumeCapabilityLabelEsUpdateEvent) {
                ResumeEs resumeEs = resumeEsService.detailById(resumeId);
                /**
                 * 能力标签
                 */
                String str = resumeCapabilityLabelService.getResumeCapabilityLabelStrByResumeId(resumeId);
                if (StringUtil.isNotObjEmpty(str)) {
                    resumeEs.setCapabilityLabel(str);
                    resumeEsService.update(resumeEs, resumeEs.getId());
                }

                return;
            }
            if (event instanceof ResumeCertificateEsUpdateEvent) {
                ResumeEs resumeEs = resumeEsService.detailById(resumeId);
                /**
                 * 证书
                 */
                String str = resumeCertificateService.getCertificateStrByResumeId(resumeId);
                if (StringUtil.isNotObjEmpty(str)) {
                    resumeEs.setCertificate(str);
                    resumeEsService.update(resumeEs, resumeEs.getId());
                }

                return;
            }
            if (event instanceof ResumeEducationalExperienceUpdateEvent) {
                ResumeEs resumeEs = resumeEsService.detailById(resumeId);

                //添加教育经历
                Map<String, Object> educationalMap = resumeEducationalExperienceService.getEducationalExperienceStrByResumeId(resumeId);
                if (StringUtil.isNotObjEmpty(educationalMap)) {
                    resumeEs.setSchool(StringUtil.toString(educationalMap.get("school")));
                    resumeEs.setSpeciality(StringUtil.toString(educationalMap.get("speciality")));
                    resumeEs.setEducation(StringUtil.toString(educationalMap.get("education")));
                    resumeEs.setEducationalExperience(StringUtil.toString(educationalMap.get("info")));
                }

                return;
            }
            if (event instanceof ResumeEmploymentIntentionUpdateEvent) {
                ResumeEs resumeEs = resumeEsService.detailById(resumeId);

                /**
                 * 意向
                 */
                String str = resumeEmploymentIntentionService.getEmploymentIntentionStrByResumeId(resumeId);
                if (StringUtil.isNotObjEmpty(str)) {
                    resumeEs.setEmploymentIntention(str);
                    resumeEsService.update(resumeEs, resumeEs.getId());
                }

                return;
            }
            if (event instanceof ResumeEmploymentIntentionUpdateEvent) {
                ResumeEs resumeEs = resumeEsService.detailById(resumeId);

                /**
                 * 实习经历
                 */
                String str = resumeIntershipService.getIntershipStrByResumeId(resumeId);
                if (StringUtil.isNotObjEmpty(str)) {
                    resumeEs.setInternship(str);
                    resumeEsService.update(resumeEs, resumeEs.getId());
                }

                return;
            }
            if (event instanceof ResumeProfessionalSkillsEsUpdateEvent) {
                ResumeEs resumeEs = resumeEsService.detailById(resumeId);

                /**
                 * 专业技能
                 */
                String str = resumeProfessionalSkillsService.getProfessionalSkillsStrByResumeId(resumeId);
                if (StringUtil.isNotObjEmpty(str)) {
                    resumeEs.setProfessionalSkills(str);
                    resumeEsService.update(resumeEs, resumeEs.getId());
                }

                return;
            }
            if (event instanceof ResumeProjectExperienceEsUpdateEvent) {
                ResumeEs resumeEs = resumeEsService.detailById(resumeId);

                /**
                 * 项目经历
                 */
                String str = resumeProjectExperienceService.getProjectExperienceStrByResumeId(resumeId);
                if (StringUtil.isNotObjEmpty(str)) {
                    resumeEs.setProjectExperience(str);
                    resumeEsService.update(resumeEs, resumeEs.getId());
                }

                return;
            }
            if (event instanceof ResumeTrainingExperienceEsUpdateEvent) {
                ResumeEs resumeEs = resumeEsService.detailById(resumeId);

                /**
                 * 培训经历
                 */
                String str = resumeTrainingExperienceService.getTrainingExperienceStrByResumeId(resumeId);
                if (StringUtil.isNotObjEmpty(str)) {
                    resumeEs.setTrainingExperience(str);
                    resumeEsService.update(resumeEs, resumeEs.getId());
                }

                return;
            }
            if (event instanceof ResumeWorkExperienceEsUpdateEvent) {
                ResumeEs resumeEs = resumeEsService.detailById(resumeId);

                /**
                 * 工作经历
                 */
                String str = resumeWorkExperienceService.getWorkExperienceStrByResumeId(resumeId);
                if (StringUtil.isNotObjEmpty(str)) {
                    resumeEs.setWorkExperience(str);
                    resumeEsService.update(resumeEs, resumeEs.getId());
                }

                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 基本信息修改
     *
     * @param resumeId
     */
    private void resumeBaseUpdate(String resumeId) {

        try {
            ResumeBasicExt resumeBasic = resumeBasicService.getDetail(resumeId);
            ResumeEs resumeEs = resumeEsService.detailById(resumeId);
            BeanUtils.copyPropertiesIgnoreNull(resumeBasic, resumeEs);
            resumeEs.setId(resumeId);
            resumeEs.setThirdAccountId(resumeBasic.getKzpStudentId());
            resumeEsService.update(resumeEs, resumeEs.getId());
        } catch (SkException e) {

        }


    }


}
